package com.code.common.utils;

import org.springframework.cglib.beans.BeanMap;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class BeanUtil<T> {

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /**
     * map转Bean
     * @param map
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> T mapToBean(Map<String, Object> map, T bean) {
        Map<String, Object> resMap = new HashMap<>();
        BeanMap beanMap = BeanMap.create(bean);
        map.forEach((k,v) ->{
            // System.out.println(k+"----"+v+"----"+v.getClass().getName());
            resMap.put(k,v);
        });
        beanMap.putAll(resMap);
        return bean;
    }

    /**
     * list<map>转List<Bean>
     */
    public static <T> List<T> mapsToBeans(List<Map<String, Object>> maps, Class<T> clazz){
        return ToolUtil.isEmpty(maps) ? Collections.emptyList() :  maps.stream().map((v) -> {
            try {
                return mapToBean(v,clazz.getDeclaredConstructor().newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
    }

    /**
     * 下划线转驼峰命名
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 将对象属性转化为map结合
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key+"", beanMap.get(key));
            }
        }
        return map;
    }








}
